package com.union.vehicleassistant.module.setting;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.widget.ContentLoadingProgressBar;

import com.blankj.utilcode.util.BusUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.data.BleScanState;
import com.hjq.base.BaseDialog;
import com.hjq.shape.view.ShapeImageView;
import com.union.vehicleassistant.R;
import com.union.vehicleassistant.action.DialogAction;
import com.union.vehicleassistant.app.AppActivity;
import com.union.vehicleassistant.bean.IBleState;
import com.union.vehicleassistant.common.Constant;
import com.union.vehicleassistant.util.BlueToothUtil;
import com.union.vehicleassistant.util.DarkModeUtils;
import com.union.vehicleassistant.util.SettingUtils;
import com.union.vehicleassistant.util.SimpleBlueToothStateChangeListener;
import com.union.vehicleassistant.util.callback.SimpleListener;
import com.union.vehicleassistant.widget.dialog.MessageDialog;

import java.text.MessageFormat;
import java.util.List;

public class BluetoothActivity extends AppActivity implements DialogAction {

    private ShapeImageView ivBleState;
    private TextView tvState, tvAction;
    private IBleState bleState = IBleState.NO_PERMISSION;
    private ContentLoadingProgressBar progressBar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bluetooth;
    }

    @Override
    protected void initView() {

        ivBleState = findViewById(R.id.iv_ble_state);
        tvState = findViewById(R.id.tv_state);
        tvAction = findViewById(R.id.tv_action);
        progressBar = findViewById(R.id.progress);

        setOnClickListener(R.id.tv_action);
    }

    @Override
    protected void initData() {
        refreshState();
        initPermission();
    }

    private void refreshState() {
        tvState.setText(bleState.descrption);
        ivBleState.setImageResource(bleState.drawableId);
        switch (bleState) {
            case NO_USABLE_DEVICE:
            case NO_PERMISSION:
            case CONNECT_FAIL:
                tvAction.setVisibility(View.VISIBLE);
                progressBar.hide();
                break;
            case SCANNING:
                tvAction.setVisibility(View.GONE);
                progressBar.show();
                break;
            default:
                tvAction.setVisibility(View.GONE);
                progressBar.hide();
                break;
        }
    }

    /**
     * 链接蓝牙
     */
    private void connectBle(String mac) {
        SettingUtils.getInstance().setConnectBleMac(mac);
        // 通知首页链接蓝牙
        BusUtils.post(Constant.BUS_CONNECT_BLUETOOTH);
    }

    /**
     * 初始化蓝牙设备
     */
    private void initPermission() {
        BlueToothUtil.initPermission(this, new BlueToothUtil.onPermissionGrantedCallback() {
            @Override
            public void onPermissionGranted(boolean b) {
                if (b) {
                    bleState = IBleState.DISCONNECT;
                    refreshState();
                    initBlueState();
                } else {
                    messageDialog(getContext(), R.string.bluetooth_without_gps_permission, new SimpleListener() {
                        @Override
                        public void onResult() {
                            initPermission();
                        }

                        @Override
                        public void onCancel() {
                            finish();
                        }
                    });
                }
            }

            @Override
            public void onUnSupport() {
                toast(R.string.bluetooth_un_support);
            }
        });
    }

    /**
     * 初始化蓝牙状态-打开
     */
    private void initBlueState() {
        boolean blueEnable = BleManager.getInstance().isBlueEnable();
        if (!blueEnable) {
            new MessageDialog.Builder(getContext())
                    .setMessage(R.string.bluetooth_without_open_tip)
                    .setListener(new MessageDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            openBlueTooth();
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            onBackPressed();
                        }
                    }).show();

        } else {
            String mac = SettingUtils.getInstance().getConnectBluetoothMac();
            if (TextUtils.isEmpty(mac)) {
                bleState = IBleState.SCANNING;
                refreshState();
                // 蓝牙设备一打开，直接扫描
                scanBluetooth();
            } else {
                boolean connected = BleManager.getInstance().isConnected(mac);
                if (connected) {
                    bleState = IBleState.CONNECTED;
                    refreshState();
                } else {
                    bleState = IBleState.CONNECTING;
                    refreshState();
                    connectBle(mac);
                }
            }
        }
    }

    /**
     * 开启蓝牙
     */
    private void openBlueTooth() {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, (resultCode, data) -> {
            if (resultCode == RESULT_OK) {
                toast(R.string.bluetooth_open_success);
                bleState = IBleState.SCANNING;
                refreshState();
                scanBluetooth();
            } else {
                toast(R.string.bluetooth_open_fail);
            }
        });
    }

    /**
     * 扫描蓝牙设备
     */
    private void scanBluetooth() {
        BlueToothUtil.scanBlueTooth(new SimpleBlueToothStateChangeListener() {
            @Override
            public void onScanning(BleDevice bleDevice) {
                super.onScanning(bleDevice);
                if (!TextUtils.isEmpty(bleDevice.getName())) {
                    bleState = IBleState.CONNECTING;
                    refreshState();
                    postDelayed(() -> connectBle(bleDevice.getMac()), 1200);
                }
            }

            @Override
            public void onScanFinish(List<BleDevice> scanResultList) {
                super.onScanFinish(scanResultList);
                if (null != scanResultList && scanResultList.size() > 0) {
                    return;
                }
                bleState = IBleState.NO_USABLE_DEVICE;
                refreshState();
                messageDialog(getContext(), getString(R.string.ble_without_device) + "\n" + getString(R.string.ble_confirm_device_open), null);
            }
        });
    }

    @Override
    public void onLeftClick(View view) {
        BleScanState scanSate = BleManager.getInstance().getScanSate();
        if (scanSate == BleScanState.STATE_SCANNING) {
            BleManager.getInstance().cancelScan();
        }
        super.onLeftClick(view);
    }

    @Override
    protected boolean isStatusBarDarkFont() {
        return !DarkModeUtils.isDarkMode(getContext());
    }

    @Override
    protected void onResume() {
        super.onResume();
        BusUtils.register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BusUtils.unregister(this);
    }

    @BusUtils.Bus(tag = Constant.BUS_KEY_BLE_FAIL)
    public void onBleConnectFail() {
        bleState = IBleState.CONNECT_FAIL;
        refreshState();
    }

    @BusUtils.Bus(tag = Constant.BUS_KEY_BLE_SUCCESS)
    public void onBleConnect(BleDevice bleDevice) {
        bleState = IBleState.CONNECTED;
        refreshState();
        tvState.setText(MessageFormat.format("{0}{1}",
                getString(R.string.ble_state_already_connect),
                bleDevice.getName()));
        toast(R.string.ble_connect_success);
    }

    @BusUtils.Bus(tag = Constant.BUS_KEY_BLE_DISCONNECT)
    public void onBleDisConnect() {
        bleState = IBleState.DISCONNECT;
        refreshState();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (bleState) {
            case NO_USABLE_DEVICE:
                messageDialog(getActivity(), R.string.ble_confirm_device_open, () -> {
                    bleState = IBleState.SCANNING;
                    refreshState();

                    scanBluetooth();
                });
                break;
            case NO_PERMISSION:
                initPermission();
                break;
            case CONNECT_FAIL:
                bleState = IBleState.SCANNING;
                refreshState();
                scanBluetooth();
                break;
        }
    }
}
